pub use pest::Parser;
pub use pest_derive::Parser;
use std::fs;
use std::env;
use std::path::{Path, PathBuf};

#[derive(Parser)]
#[grammar = "csv.pest"]
pub struct CSVParser;

pub fn test_csv() {
    // let successful_parse = CSVParser::parse(Rule::field, "-273.15");
    // println!("{:?}", successful_parse);
    // let unsuccessful_parse = CSVParser::parse(Rule::field, "this is not a number");
    // println!("{:?}", unsuccessful_parse);

    let file_name = "numbers.csv"; 
    let mut file_path = env::current_dir().unwrap();
    file_path.push("src");
    file_path.push(file_name);

    let unparsed_file = fs::read_to_string(file_path).expect("cannot read file");
    let file = CSVParser::parse(Rule::file, &unparsed_file)
        .expect("unsuccessful parse") // unwrap the parse result
        .next().unwrap(); // get and unwrap the `file` rule; never fails
    let tokens = file.clone().tokens();
    for tk in tokens {
        println!("{:?}", tk);
    }

    let mut field_sum: f64 = 0.0;
    let mut record_count: u64 = 0;

    for record in file.into_inner() {
        match record.as_rule() {
            Rule::record => {
                record_count += 1;

                for field in record.into_inner() {
                    field_sum += field.as_str().parse::<f64>().unwrap();
                }
            }
            Rule::EOI => (),
            _ => unreachable!(),
        }
    }

    println!("Sum of fields: {}", field_sum);
    println!("Number of records: {}", record_count);

}

pub fn peek_path() {
    const PROJECT_ROOT: &str = env!("CARGO_MANIFEST_DIR"); 
    let root_path = Path::new(PROJECT_ROOT); // 项目根目录
    println!("proj root path: {:?}", root_path);

    let exe_path = env::current_exe().unwrap(); 
    println!("exe path: {:?}", exe_path);

    let current_dir = env::current_dir().unwrap();
    println!("cwd : {:?}", current_dir);
}